package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.util.Utils;
import sk.naive.talker.adapter.Adapter;
import sk.naive.talker.message.DefaultMessageFactory;

import java.rmi.RemoteException;
import java.lang.reflect.*;
import java.util.Date;

/**
 *
 * @author <a href="mailto:richter@bgs.sk">Richard Richter</a>
 * @version $Revision: 1.18 $ $Date: 2005/01/08 14:17:35 $
 */
public class Sysinfo extends AbstractCommand {
	public void exec()
		throws CommandException,
		RemoteException
	{
		Runtime runtime = Runtime.getRuntime();

		StringBuilder sb = new StringBuilder();
		sb.append(getString("sysinfo.head", user.getProperties()));
//		showMBean(ManagementFactory.getRuntimeMXBean(), RuntimeMXBean.class);
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + 0, runtime.availableProcessors());
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + 1, runtime.maxMemory());
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + 2, runtime.totalMemory());
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + 3, runtime.freeMemory());
		sb.append(getString("sysinfo.main", user.getProperties()));
		sb.append(getString("sysinfo.adapters", user.getProperties()));

		for (AdapterProxy a : getTalker().getAdapters()) {
			ctxSet(DefaultMessageFactory.CTXKEY_VAL, a.getName());
			ctxSet(DefaultMessageFactory.CTXKEY_VAL + "created", Utils.createDate(a.get(Adapter.APROP_CREATED)));
			sb.append(getString("sysinfo.adapterLine", user.getProperties()));
		}

		sb.append(getString("sysinfo.timers", user.getProperties()));
		for (TimerTask task : getTalker().timerService().tasks()) {
			ctxSet(DefaultMessageFactory.CTXKEY_VAL, task.getName());
			ctxSet(DefaultMessageFactory.CTXKEY_VAL + "count", task.getCount());
			ctxSet(DefaultMessageFactory.CTXKEY_VAL + "nearest", new Date(task.scheduledExecutionTime()));
			sb.append(getString("sysinfo.timerTaskLine", user.getProperties()));
		}

		sb.append(getString("sysinfo.tail", user.getProperties()));
		user.send(sb.toString());
	}

	// TODO premysliet, co s mbeanmi
	private void showMBean(Object mBean, Class mBeanClass) {
		for (Method method : mBeanClass.getDeclaredMethods()) {
			if (method.getParameterTypes().length != 0) {
				continue;
			}
			String methodName = method.getName();
			if (methodName.startsWith("get") || methodName.startsWith("is")) {
				try {
					String out = methodName + " = " + method.invoke(mBean, new Object[0]);
				} catch (IllegalAccessException e) {
					Utils.unexpectedExceptionWarning(e);
				} catch (InvocationTargetException e) {
					Utils.unexpectedExceptionWarning(e);
				}
			}
		}
	}
}
